import { LookupListItem } from "@/typings/api";
import type { EditableFormInstance, ProColumns } from "@ant-design/pro-components";
import { EditableProTable } from "@ant-design/pro-components";
import { forwardRef, ForwardRefRenderFunction, useContext, useImperativeHandle, useRef } from "react";
import { CodeGenerateConfigContext } from "../CodeGenerateConfig";
import { Button } from "antd";
import { getUUID } from "@/utils";

export interface LookupListRef {
    getRowsData: () => LookupListItem[];
    validate: () => Promise<Record<number, LookupListItem>>;
}

const LookupList: ForwardRefRenderFunction<LookupListRef, {}> = (_props, ref) => {
    const { lookupList, setLookupList } = useContext(CodeGenerateConfigContext);
    const columns: ProColumns<LookupListItem>[] = [
        {
            dataIndex: "modelName",
            title: "子模型名",
            formItemProps: {
                rules: [{ required: true, message: "子模型名为必填项" }],
            },
        },
        {
            dataIndex: "from",
            title: "子表名",
            formItemProps: {
                rules: [{ required: true, message: "子表名为必填项" }],
            },
        },
        {
            dataIndex: "localField",
            title: "关联字段名",
            formItemProps: {
                rules: [{ required: true, message: "关联字段名为必填项" }],
            },
        },
        {
            dataIndex: "as",
            title: "关联查询新字段名",
        },
        {
            dataIndex: "foreignField",
            title: "子表关联字段名",
        },
        {
            title: "操作",
            valueType: "option",
            width: 100,
        },
    ];
    const tableRef = useRef<EditableFormInstance<LookupListItem>>();
    useImperativeHandle(ref, () => ({
        getRowsData: () => tableRef.current?.getRowsData?.() || [],
        validate: () => tableRef.current!.validateFields() as unknown as Promise<Record<number, LookupListItem>>,
    }));
    return (
        <>
            <EditableProTable<LookupListItem>
                editableFormRef={tableRef}
                rowKey="_id"
                columns={columns}
                dataSource={lookupList}
                value={lookupList}
                onChange={setLookupList}
                editable={{
                    type: "multiple",
                    editableKeys: lookupList.map(item => item._id!),
                    actionRender: (row, config, defaultDom) => [
                        <Button danger type="link">
                            {defaultDom.delete}
                        </Button>,
                    ],
                }}
                recordCreatorProps={{
                    newRecordType: "dataSource",
                    record: index => ({
                        _id: getUUID(),
                        from: "",
                        localField: "",
                    }),
                }}
            />
        </>
    );
};

export default forwardRef(LookupList);
